/*
* Copyright 2011 Andy Lee.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package uk.co.optimisticpanda.remoteweb.main

import javax.xml.XMLConstants
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.SchemaFactory

import org.openqa.selenium.firefox.FirefoxDriver
import org.xml.sax.SAXParseException

import uk.co.optimisticpanda.remoteweb.command.CommandUtils
import uk.co.optimisticpanda.remoteweb.command.xml.CommandXmlUnmarshaller

dir = new File("./scripts/")
println "Watching for scripts:\t" + dir.absolutePath


println "Initialising Firefox Driver."
def driver = new FirefoxDriver();

while(true){
	try{
		chooseScript(driver, dir)
	}catch(RuntimeException e){
		println e.printStackTrace()
	}
}

def chooseScript(driver, dir){
	scripts = dir.listFiles()
	
	scripts.inject(0){count, it ->
		println "" + count + ":\t" + it.name 
		++count;
		}
	
	println "Press Enter script number to run: "
	index = Integer.valueOf (new Scanner(System.in).nextLine())
	
	def file = scripts[index]
	if (validate(file)){
		def commandSet =  new CommandXmlUnmarshaller().unmarshal(file.text)
		commandSet.run(driver)
	}
}

def validate(file){
	assert "File must exist!" : file.exists()
	def factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
	def schema = factory.newSchema(new StreamSource(new FileReader("commands.xsd")))
	def validator = schema.newValidator()
	try{
		validator.validate(new StreamSource(new FileReader(file)))
	}catch(SAXParseException e){
		e.printStackTrace()
		return false;
	}catch(RuntimeException e){
		e.printStackTrace()
		return false;
	}
	return true;
}
